package com.lmind.core.gps.terminal.protocol;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

public class PacketCodec {

//	public byte[] encode(byte[] data) throws Exception {
//		
//		if (data.length > PacketConstants.MAX_BODY_SIZE) {
//			throw new PacketException("消息内容不能超过" + PacketConstants.MAX_BODY_SIZE);
//		}
//		
//		ByteBuffer buff = ByteBuffer.allocateDirect(data.length + PacketConstants.HEADER_SIZE);
//
//		buff.putInt(PacketConstants.MAGIC_NUMBER);
//		buff.putInt(PacketConstants.VERSION);
//		buff.putInt(data.length);
//		buff.put(data);
//		
//		return null;
//	}
	
	public ByteBuffer encode(ByteBuffer data) throws Exception {
		
		if (data.remaining() > PacketConstants.MAX_BODY_SIZE) {
			throw new PacketException("消息内容不能超过" + PacketConstants.MAX_BODY_SIZE);
		}
		
		ByteBuffer buff = ByteBuffer.allocate(data.remaining() + PacketConstants.HEADER_SIZE);

		buff.putInt(PacketConstants.MAGIC_NUMBER);
		buff.putInt(PacketConstants.VERSION);
		buff.putInt(data.remaining());
		buff.put(data);
		buff.rewind();
		return buff;
	}
	
	public byte[] decode(byte[] packet) {
		
		ByteBuffer buff = ByteBuffer.wrap(packet);
		PacketHeader header = checkHeader(buff);
		if (header == null)
			return null;
		if (header.getBodySize() > packet.length - PacketConstants.HEADER_SIZE) {
			return null;
		}
		
		byte[] data = new byte[header.getBodySize()];
		buff.get(data);
		return data;
	}
	
	public ByteBuffer decode(ByteBuffer packet) {
		
		PacketHeader header = checkHeader(packet);
		if (header == null)
			return null;
		if (header.getBodySize() > packet.remaining()) {
			return null;
		}
		
		byte[] body = new byte[header.getBodySize()];
		packet.get(body);
		
		return ByteBuffer.wrap(body);
	}
	
	protected PacketHeader checkHeader(ByteBuffer buff) {
		
		if (buff.remaining() < PacketConstants.HEADER_SIZE)
			return null;
		
		int magicNumber = buff.getInt();
		int version = buff.getInt();
		int size = buff.getInt();
		
		if (magicNumber != PacketConstants.MAGIC_NUMBER && version != PacketConstants.VERSION) {
			throw new PacketException("非法的头");
		}
		if (size > PacketConstants.MAX_BODY_SIZE) {
			throw new PacketException("消息内容不能超过" + PacketConstants.MAX_BODY_SIZE);
		}
		
		PacketHeader header = new PacketHeader();
		header.setVersion(version);
		header.setBodySize(size);
		return header;
	}
}
